package com.guigutool.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigutool.reggie.common.CustomException;
import com.guigutool.reggie.dto.SetmealDto;
import com.guigutool.reggie.entity.Setmeal;
import com.guigutool.reggie.entity.SetmealDish;
import com.guigutool.reggie.mapper.SetmealMapper;
import com.guigutool.reggie.service.SetmealDishService;
import com.guigutool.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: KingWang
 * @Date: 2023/3/12
 * @Desc:
 **/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增套餐，同时保存套餐和菜品的关联关系
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);
        Long setmealId = setmealDto.getId();
        //保存套餐和菜品的关联信息
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes().stream().map(x->{
            x.setSetmealId(setmealId);
            return x;
        }).collect(Collectors.toList());
        String key = "setmeal:" + setmealDto.getId();
        redisTemplate.delete(key);
        setmealDishService.saveBatch(setmealDishList);
    }


    /**
     * 删除套餐，同时删除套餐和菜品的关联数据
     * @param ids
     */
    @Transactional
    @Override
    public void removeWithDish(List<String> ids) {
        //查询套餐状态，确定是否删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(queryWrapper);
        if(count > 0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        //如果可以删除，先删除套餐表中的数据
        this.removeByIds(ids);
        //删除关系表中的数据
        LambdaQueryWrapper<SetmealDish> queryWrapperDish = new LambdaQueryWrapper<>();
        queryWrapperDish.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapperDish);
        String key = "setmeal:*";
        redisTemplate.delete(key);

    }
}
